/*
 * @description:
 * @author: JXY
 * @Date: 2019-05-07 16:05:33
 * @Email: JXY001a@aliyun.com
 * @LastEditTime: 2019-12-03 14:42:19
 */
/**
 * @description 常用的工具方法
 * @Time 2018-05-31
 * @author JXY
 */
import $ from "jquery";
import {ACCESS_MARK,ACCESS_PAGE,ACCESS_TOKEN_STORAGE_KEY, ACCESS_VALUE} from '../config';

/**********************PUBLIC FUNCTION START*****************************/
//设置延时
export function delay(timeout) {
    var pro = new Promise(function(resolve, reject) {
        setTimeout(resolve, timeout);
    });
    return pro;
}

//筛选需要处理的数据更新form的数据
/*
    columns: 需要传到后端的字段
    editItem: 对象所有数据
*/
export function handleEditItem(columns, editItem) {
    var newItem = {};
    columns.map((item) => {
        newItem[item] = editItem[item];
    });
    return newItem;
}

// 根据 url 获取指定参数
/*
    name: 键值 key
    url: 指定提取参数的url 默认使用 window.location.href
*/
export function getParamterByName(name, url) {
    url = isString(url) ? url : window.location.href;
    let regex = new RegExp("[?&]" + name + "(=([^&#?]*)|#|&|$)");
    var result = regex.exec(url);
    if (!isArray(result)) return null;
    if (!isString(result[2])) return null;
    return result[2];
}

// 返回任意数据类型的类型
export function getObjType(obj) {
    return Object.prototype.toString.call(obj);
}
/**********************PUBLIC FUNCTION END*****************************/


/**********************具体工具 FUNCTION START*************************/
// 是否为数组  Array
export function isArray(obj) {
    return getObjType(obj) == "[object Array]";
}
// 是否为字符串 String
export function isString(obj) {
    return getObjType(obj) == "[object String]";
}
// 是否为 undefined
export function isUndefined(obj) {
    return getObjType(obj) == "[object Undefined]";
}
// 是否为数字 number
export function isNumber(obj) {
    return getObjType(obj) == "[object Number]";
}
// 是否为 Date
export function isDate(obj) {
    return getObjType(obj) == "[object Date]";
}
// 是否为 function
export function isFunction(obj) {
    return getObjType(obj) == "[object Function]";
}
// 是否为 null
export function isNull(obj) {
    return getObjType(obj) == "[object Null]";
}
// 是否为 Object
export function isObject(obj) {
    return getObjType(obj) == "[object Object]";
}
// 获取token
export function getToken() {
    if(getParamterByName("access_token",null)) {
        return getParamterByName("access_token",null);
    }
    if(localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY)) {
        return localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY);
    }
    return "be5f2257-f7a8-4d8d-9c8b-77cbacc159d8";
}
// 获取systemId
export function getSystemId() {
    return getParamterByName("systemId",null) || "";
}
// 获取systemCode
export function getSystemCode() {
    return getParamterByName("systemCode", null) || "";//
}
// 获取租户 tenantId
export function getTenantId() {//
    return getParamterByName("tenantId", null) || "0ff83c7c50d340d6a95c576387715b9d";//
}
// 获取用户 userId
export function getUserId() {
    return getParamterByName("userId",null) || "";//0d3782b5d09e4075b05d2e8cc7303530
}

// 获取用户 userName
export function getUserName() {
    return getParamterByName("userName",null) || "admin_zsf";
}


// 为请求参数添加公共参数
export function addPublicParams(data) {
    // data.userId = getUserId();
    data.tenantId = getTenantId();
    // data.userName = getUserName();
    data.systemCode = getSystemCode();
    // data.tid = getTenantId();
    // 使用时间戳来保证每此请求都是一个新的请求，防止IE的缓存机制
    data.forIeNoCache = new Date().getTime();
    return data;
}
//序列化数据
export function jsonToUrl(jsonData) {
    let html = "";
    for (let i in jsonData) {
        html += `&${i}=${jsonData[i]}`
    }
    return html.slice(1);
}

export function formatData(str,format){
    var oDate = str?new Date(str):new Date(),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth()+1,
    oDay = oDate.getDate(),
    oHour = oDate.getHours(),
    oMin = oDate.getMinutes(),
    oSen = oDate.getSeconds();
    let oTime = '';
    if(format && format.length==10){
        oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay);
    }else {
        oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay) +' '+ getzf(oHour) +':'+ getzf(oMin) +':'+getzf(oSen);//最后拼接时间
    }
    return oTime;
};
//不要时分秒的时间戳转化
export function formatDataDay(str,format){
    var oDate = str?new Date(str):new Date(),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth()+1,
    oDay = oDate.getDate(),
    oHour = oDate.getHours(),
    oMin = oDate.getMinutes(),
    oSen = oDate.getSeconds();
    let oTime = '';
    if(format && format.length==10){
        oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay);
    }else {
        oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay) //最后拼接时间
    }
    return oTime;
};
//补0操作
export function getzf(num){
    if(parseInt(num) < 10){
        num = '0'+num;
    }
    return num;
}
/**********************具体工具 FUNCTION END*************************/

export function downloadFile(url, options) {
    $('body').append('<form id="downloadForm" style="display:none" target="" method="get"></form>');
    var param = options;
    var html = "";
    for(var key in param){
        html+=`<input type=hidden name='${key}' value='${param[key]}' />`;
    }
    $("#downloadForm").append(html);
    $("#downloadForm").attr("action",url);
    $("#downloadForm").submit();
    $("#downloadForm").remove();
}

export function downLoadFileNew(reqURL, param) {
    window.open(`${reqURL}?${$.param(param, true)}` + '&access_token=' + getParamterByName('token'));
}
export function getInfoByAjax(options,sucCallback) {
    let url = options.url;
    let data = options.data;
    if (!url || !data) {
        return sucCallback();
    }
    $.ajax({
        type:"GET",
        url:url,
        data:{
            ...data,
            tenantId:getTenantId(),
            userId:getUserId(),
        },
        success:(data) =>{
            sucCallback(data);
        }
    });
}
//树
export function selectTreeDataProcessor(data,nodeTypeName=undefined){

    if(nodeTypeName!=undefined){
        return data.map((item)=>{
            const attr = {
                ...item,
                value: item.id,
                key: item.id,
                id: item.id,
                label: item.name,
                isLeaf:item.leaf==='false'?false:true,
                nodeType:item.nodeType,
                disabled:item.nodeType==nodeTypeName,
            }
            if(item.children && item.children.length > 0){
                attr.children = selectTreeDataProcessor(item.children,nodeTypeName)
            }
            return attr;
        });
    }else{
        return data.map((item)=>{
            const attr = {
                ...item,
                value: item.id,
                key: item.id,
                id: item.id,
                label: item.name,
                title: item.name,
                isLeaf:item.leaf==='false'?false:true,
                nodeType:item.nodeType,
            }
            if(item.children && item.children.length > 0){
                attr.children = selectTreeDataProcessor(item.children)
            }
            return attr;
        });
    }
}

export function geKeyValueFromArrObj(arr,id) {
    let needObj = {};
    if (!Array.isArray(arr) || typeof id !== 'string') return needObj;
    arr.forEach((item)=>{
        if (item && item['id']) {
            if (id === item['id']) {
                return needObj = {...item};
            }
        }
    });
    return needObj;
}

// 设置title标签
export function setHtmlTitle(title) {
    title = title || "收集点管理";
    $("title")[0].innerText = title;
}

// 当天开始时间
export function getTodayBeginTime() {
    return new Date(new Date(new Date().toLocaleDateString()).getTime());
}
// 当天结束时间
export function getTodayEndTime() {
    return new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1);
}

/**
 * @description: 校验异步请求是否成功
 * @author: JXY
 * @param {object:result}
 * @return:
 * @Date: 2019-01-03 15:43:07
 */
export function verifyAsyncResult(result) {
    let verifyResult = {
        isSuccess:false,
        msg:'数据加载错误',
    };
    if(result) {
        if(result.result === 0) {
            verifyResult.isSuccess = true;
            verifyResult.msg = '数据加载成功！';
        }else{
            verifyResult.isSuccess = false;
            verifyResult.msg = result.msg ? result.msg : '数据加载失败！';
        }
    }
    return verifyResult;
}

//判断是否为空
export function empty(vars) {
    let result = false;
    if (vars) {
      if (typeof(vars) == 'object') {
        if (vars instanceof Object && Object.keys(vars).length == 0) {
          result = true;
        } else if (vars instanceof Array && vars.length == 0) {
          result = true;
        }
      }
    } else {
      result = true;
    }
    return result;
  }
//获取当前body高度
export function getBodyHeight(minus) {
    minus = parseInt(minus);
    if (empty(minus))
      return document.body.offsetHeight;
    else
      return document.body.offsetHeight - minus;
  }

export  function getBodyWidth(minus) {
    minus = parseInt(minus);
    if (empty(minus))
      return document.body.offsetWidth;
    else
      return document.body.offsetWidth - minus;
  }
//滚动设置
export function wresize(callback) {
    $(window).unbind()
    $(window).resize(callback);
    $(window).resize();
}

// 判断字符串是否为url
export function isUrl(path) {
    const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
    return reg.test(path);
}
// 判断数组中某元素的个数
export function getElementNum(arr,ele){
    var temp=[];
    for(var index=0;index<arr.length;index++){
        if(arr[index]==ele){
            temp.push(true);
        }
    }
    return temp.length;
}
/**
 * @description:返回一个url中的host地址
 * @author: JXY
 * @Date: 2019-03-01 10:02:03
 */
export function getHost(url) {
    if(typeof url!=='string') return undefined;
    // 正则匹配 hostMsg == ['主机号','ip','端口号'];
    const hostMsg = /^http:\/\/(.*):([0-9]{4,5})\//.exec(url);
    const Host = hostMsg[0]||undefined;
    return Host;
}
// 生成指定dom节点append到body中
export function createDomAppendBody({type,options}) {
    let dom = document.createElement(typeof type === 'string'?type:'div');
    if(options || typeof options === 'object') {
        for(let key in options) {
            dom[key] = options[key];
        }
    }
    document.body.appendChild(dom);
}

// 路线<String> 转换为 <Array> 即:'120.12,32.32;120.12,32.32;' -> [[120.12,32.32],[120.12,32.32]]
export function pathStrToArray(path) {
    if(typeof path !== 'string')
        return [];
    return path.split(';').filter(({length})=>length).map(item=>item.split(','));
}
// 路线<Array> 转换为 <string> 即:[[120.12,32.32],[120.12,32.32]] -> '120.12,32.32;120.12,32.32;'
export function arrayToString(pathArr) {
    if(!Array.isArray(pathArr))
        return [];
    return pathArr.map((item)=>item.join(',')).join(';');
}
// 格式化数据,指定数位数digits(取值范围0~20之间)
export function getFixedNum (number,digits=2) {
    number = parseFloat(number);
    digits = parseInt(digits);

    digits = typeof digits !='number'?2:digits
    if(typeof number === "number") {
        if(digits>20) {
            digits = 20;
        }
        if(digits<0) {
            digits = 0;
        }
        return number.toFixed(digits);
    }
    return 0.00;
}

// 打开至指定系统及其中的指定页面
export function goSysPage({page,sysCode}) {
    const nowSysCode = getSystemCode();
    const sysCodePrefix = nowSysCode.substr(0,nowSysCode.indexOf('_'));
    const topWindow = window.top;
    let url = topWindow.location.href;
    url = url.substr(0,url.indexOf("?"));
    topWindow.open(`${url}?userId=${getUserId()}&tenantId=${getTenantId()}&access_token=${getToken()}&systemCode=${sysCodePrefix}_${sysCode}&${ACCESS_MARK}=true&${ACCESS_PAGE}=${page}`);
}

// 打开至指定系统及其中的指定页面+传参
export function goSysPageById({ page, sysCode, carId }) {
    console.log(page, sysCode, carId, nowSysCode)
    const nowSysCode = getSystemCode();
    const sysCodePrefix = nowSysCode.substr(0, nowSysCode.indexOf('_'));
    const topWindow = window.top;
    let url = topWindow.location.href;
    url = url.substr(0, url.indexOf("?"));
    topWindow.open(`${url}?userId=${getUserId()}&tenantId=${getTenantId()}&access_token=${getToken()}&systemCode=${sysCodePrefix}_${sysCode}&${ACCESS_MARK}=true&${ACCESS_PAGE}=${page}&${ACCESS_VALUE}=${carId}`);
}

export function gotoNewPage(page) {
    window.location.href = getHost(window.location.href) + page;
}

/* 跳转至指定路由 */
export const goToSomePage = (page)=>{
    let url = window.location.href;
    const topWindow = window.top;
    // 正则匹配类型 => #/<路由>?
    // 例子 => #/welcomePage?
    // replace(regexp|substr,newSubStr|function<replacement>)
    // replacement 参数问题 ，param1:匹配的子串,param2:$1,param3:$3,……，倒数第二(offset)：匹配到的子字符串在原字符串中的偏移量,last:被匹配的原字符串
    topWindow.location.href = url.replace(/#\/([a-zA-Z]{1,})\??/,(match,$1)=>{
        return match.replace($1,page);
    });
}
// 首字母大写 其他小写
function titleCase(str) {
    var array = str?str.toLowerCase().split(" "):'';
    for (var i = 0; i < array.length; i++){
      array[i] = array[i][0].toUpperCase() + array[i].substring(1, array[i].length);

    }
    var string = array.join(" ");
    return string;
  }

export function goToWelComePage() {
    const topWindow = window.top;
    const URL = topWindow.location.href;
    topWindow.location.href =  /(http|https):\/{2,2}(.*):([0-9]){4,5}/.exec(URL)[0];
}
